<template>
  <r-header />
  <div class="result-container">
    <!-- 结果概览 -->
    <div class="result-overview">
      <div class="result-header">
        <button class="btn-secondary" @click="goBack">返回首页</button>
        <h2>试卷详情</h2>
        <button class="btn-primary" @click="goToTestHistory">考试记录</button>
      </div>
      <div class="score-card">
        <div class="score-section">
          <div class="score-label">得分</div>
          <div class="score-value">{{ score }} / {{ totalQuestions }}</div>
        </div>
        <div class="divider"></div>
        <div class="score-section">
          <div class="score-label">正确率</div>
          <div class="score-value">{{ percentage }}%</div>
          <div class="score-level">{{ scoreLevel }}</div>
        </div>
      </div>
    </div>
    <!-- AI点评 -->
    <div class="ai-comment">
      <div class="comment-header">
        <div class="ai-icon">🤖</div>
        <h3>AI点评</h3>
      </div>
      <div class="comment-content">
        <p v-if="aiComment && aiComment.trim()">
          {{ aiComment }}
        </p>
        <p v-else-if="aiCommentLoaded" class="no-comment">
          暂无AI点评
        </p>
        <p v-else class="loading-comment">
          正在生成AI点评...
        </p>
      </div>
    </div>
    <!-- 题目列表 -->
    <div class="questions-list">
      <div 
        v-for="(question, index) in questions" 
        :key="index"
        class="question-item"
        :class="{ 'correct': question.isCorrect, 'incorrect': !question.isCorrect }"
      >
        <div class="question-header">
          <span class="question-number">第 {{ index + 1 }} 题</span>
          <span class="result-badge" :class="question.isCorrect ? 'correct-badge' : 'incorrect-badge'">
            {{ question.isCorrect ? '✓ 正确' : '✗ 错误' }}
          </span>
        </div>

        <div class="question-text">{{ question.question }}</div>

        <div class="options-list">
          <div 
            v-for="(option, optionIndex) in question.options" 
            :key="optionIndex"
            class="option-item"
            :class="{
              'user-selected': question.userAnswer === optionIndex,
              'correct-answer': question.correctAnswer === optionIndex
            }"
          >
            <span class="option-label">{{ String.fromCharCode(65 + optionIndex) }}.</span>
            <span class="option-text">{{ option }}</span>
            <span v-if="question.userAnswer === optionIndex" class="tag user-tag">你的答案</span>
            <span v-if="question.correctAnswer === optionIndex" class="tag correct-tag">正确答案</span>
          </div>
        </div>
      </div>
    </div>

    
  </div>
</template>

<script>
export default {
  name: 'TestResult',
  data() {
    return {
      questions: [],
      score: 0,
      totalQuestions: 0,
      aiComment: '', // 添加AI点评字段
      aiCommentLoaded: false // 标记AI点评是否已加载完成
    }
  },
  computed: {
    percentage() {
      if (this.totalQuestions === 0) return 0;
      return Math.round((this.score / this.totalQuestions) * 100);
    },
    scoreLevel() {
      const p = this.percentage;
      if (p >= 90) return '优秀';
      if (p >= 80) return '良好';
      if (p >= 60) return '及格';
      return '需努力';
    }
  },
  mounted() {
    this.loadResultData();
  },
  methods: {
    async loadResultData() {
      // 优先从URL参数获取paperId（从考试记录页面跳转过来）
      // 使用Vue Router的$route.query而不是URLSearchParams
      let paperIdFromUrl = this.$route.query.paperId;
      
      // 如果Vue Router的query参数为空，尝试从URL直接解析
      if (!paperIdFromUrl) {
        const urlParams = new URLSearchParams(window.location.search);
        paperIdFromUrl = urlParams.get('paperId');
      }
      
      console.log('当前路由:', this.$route);
      console.log('路由参数:', this.$route.query);
      console.log('当前URL:', window.location.href);
      console.log('URL参数:', window.location.search);
      console.log('获取到的paperId:', paperIdFromUrl);
      
      if (paperIdFromUrl) {
        // 从后端加载试卷详情
        await this.loadPaperFromBackend(paperIdFromUrl);
      } else {
        // 从localStorage加载（新答题完成的情况）
        const savedQuestions = localStorage.getItem("generatedQuestions");
        const savedAnswers = localStorage.getItem("userAnswers");
        const paperId = localStorage.getItem("paperId");
        
        if (!savedQuestions) {
          alert('未找到题目数据，将返回首页');
          this.$router.push('/');
          return;
        }
        
        this.loadFromLocalStorage(savedQuestions, savedAnswers, paperId);
      }
    },
    
    // 从后端加载试卷详情
    async loadPaperFromBackend(paperId) {
      try {
        console.log('调用后端API获取试卷详情，paperId:', paperId);
        const response = await fetch(`http://localhost:8088/api/test-paper/${paperId}`);
        const result = await response.json();
        
        console.log('后端API响应:', result);
        
        if (result.code === 200 && result.data) {
          const data = result.data;
          
          // 加载AI点评
          this.aiComment = data.aiComments || '';
          this.aiCommentLoaded = true; // 标记AI点评已加载完成
          
          // 解析题目数据
          if (data.questions && Array.isArray(data.questions)) {
            this.processQuestions(data.questions);
          } else {
            throw new Error('试卷数据格式错误');
          }
        } else {
          throw new Error(result.msg || '加载试卷失败');
        }
      } catch (error) {
        console.error('加载试卷失败:', error);
        alert('加载试卷失败，将返回首页');
        this.$router.push('/my');
      }
    },
    
    // 处理题目数据
    processQuestions(questionsData) {
      this.totalQuestions = questionsData.length;
      
      this.questions = questionsData.map((q, index) => {
        // 解析选项
        const options = [];
        if (q.options && typeof q.options === 'object') {
          options.push(q.options.A || '');
          options.push(q.options.B || '');
          options.push(q.options.C || '');
          options.push(q.options.D || '');
        }
        
        // 获取正确答案
        const correctAnswer = this.getCorrectAnswerIndex(q.correctanswer || q.correct_answer || '');
        
        // 获取用户答案
        const userAnswer = q.useranswer || '';
        const userAnswerIndex = this.getCorrectAnswerIndex(userAnswer);
        
        const isCorrect = userAnswer && userAnswerIndex === correctAnswer;
        
        if (isCorrect) {
          this.score++;
        }
        
        return {
          question: q.question,
          options: options,
          correctAnswer: correctAnswer,
          userAnswer: userAnswer ? userAnswerIndex : -1,
          isCorrect: isCorrect
        };
      });
    },
    
    // 从localStorage加载数据
    loadFromLocalStorage(savedQuestions, savedAnswers, paperId) {
      try {
        this.questions = JSON.parse(savedQuestions);
        const answers = savedAnswers ? JSON.parse(savedAnswers) : [];
        this.totalQuestions = this.questions.length;

        // 处理每道题的结果
        this.questions = this.questions.map((q, index) => {
          const userAnswer = answers[index];
          const correctAnswer = q.correct;
          const isCorrect = userAnswer === correctAnswer;

          if (isCorrect) {
            this.score++;
          }

          return {
            question: q.question,
            options: q.options,
            correctAnswer: correctAnswer,
            userAnswer: userAnswer !== null ? userAnswer : -1,
            isCorrect: isCorrect
          };
        });

        // 从后端获取AI点评
        if (paperId) {
          this.loadAIComment(paperId);
        }
      } catch (error) {
        console.error('加载结果数据失败:', error);
        alert('数据加载失败');
        this.$router.push('/');
      }
    },
    
    // 获取正确答案索引
    getCorrectAnswerIndex(correctAnswer) {
      const answerMap = { 'A': 0, 'B': 1, 'C': 2, 'D': 3 };
      return answerMap[correctAnswer] || 0;
    },
    
    async loadAIComment(paperId) {
      // 初始不设置任何文案，保持aiComment为空字符串，显示"正在生成AI点评..."
      
      const defaultComment = `本次测试您答对了 ${this.score} 道题，正确率 ${this.percentage}%。通过本次练习，您可以清楚地了解自己对知识点的掌握情况。对于答对的题目，说明这部分内容您理解得很好。而对于错题，这正是您需要重点关注和加强的地方。建议您针对错题进行专项复习，深入理解相关的知识点。可以重新查阅教材、做相关练习题，确保完全掌握。同时，也要保持对已掌握知识的复习，以巩固学习成果。`;
      
      // 轮询获取AI点评，最多尝试10次
      let retryCount = 0;
      const maxRetries = 10;
      const pollInterval = 2000; // 2秒轮询一次
      
      const pollAIComment = async () => {
        try {
          const response = await fetch(`http://localhost:8088/api/test-paper/${paperId}`);
          const result = await response.json();
          
          if (result.code === 200 && result.data && result.data.aiComments && result.data.aiComments.trim()) {
            // 获取到AI点评，更新显示
            this.aiComment = result.data.aiComments;
            this.aiCommentLoaded = true;
            console.log('AI点评加载成功');
          } else if (retryCount < maxRetries) {
            // 还没生成完成，继续轮询
            retryCount++;
            setTimeout(pollAIComment, pollInterval);
          } else {
            // 超时了，检查是否有AI点评内容
            if (result.code === 200 && result.data && result.data.aiComments !== null) {
              // 有数据但为空，显示暂无AI点评
              this.aiComment = '';
              this.aiCommentLoaded = true;
              console.log('AI点评为空，显示暂无AI点评');
            } else {
              // 超时了，显示默认文案
              console.log('AI点评生成超时，使用默认文案');
              this.aiComment = defaultComment;
              this.aiCommentLoaded = true;
            }
          }
        } catch (error) {
          console.error('获取AI点评失败:', error);
          // 出错时显示默认文案
          this.aiComment = defaultComment;
          this.aiCommentLoaded = true;
        }
      };
      
      // 立即开始第一次请求
      pollAIComment();
    },
    goBack() {
      // 清空相关数据
      localStorage.removeItem("generatedQuestions");
      localStorage.removeItem("userAnswers");
      localStorage.removeItem("paperId");
      this.$router.push('/');
    },
    goToTestHistory() {
      // 跳转到考试记录页面
      this.$router.push('/test-history');
    }
  }
}
</script>

<style lang="scss" scoped>
.result-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
  padding-top: 100px;
  padding-bottom: 30px;
  color: #ffffff;
}

.ai-comment {
  max-width: 1200px;
  margin: 0 auto 1.5rem;
  padding: 0 1.5rem;

  .comment-header {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    margin-bottom: 0.75rem;

    .ai-icon {
      font-size: 1.5rem;
      filter: drop-shadow(0 0 8px rgba(59, 130, 246, 0.5));
    }

    h3 {
      color: #3b82f6;
      font-size: 1.25rem;
      margin: 0;
      font-weight: 600;
    }
  }

  .comment-content {
    background: rgba(59, 130, 246, 0.1);
    border: 1px solid rgba(59, 130, 246, 0.3);
    border-radius: 10px;
    padding: 1rem 1.25rem;
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);

    p {
      color: #e5e7eb;
      font-size: 0.9rem;
      line-height: 1.6;
      margin: 0;
    }

    .loading-comment {
      color: #9ca3af;
      font-style: italic;
      animation: pulse 2s ease-in-out infinite;
    }

    .no-comment {
      color: #6b7280;
      font-style: italic;
      text-align: center;
      padding: 1rem;
      background: rgba(255, 255, 255, 0.03);
      border-radius: 8px;
      border: 1px solid rgba(255, 255, 255, 0.1);
    }
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

.result-overview {
  max-width: 1200px;
  margin: 0 auto 1rem;
  padding: 0 1.5rem;

  .result-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1rem;
    margin-bottom: 0.75rem;

    button {
      padding: 0.5rem 1rem;
      border-radius: 8px;
      font-size: 0.8rem;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.3s ease;
      border: 1px solid rgba(255, 255, 255, 0.2);
      backdrop-filter: blur(10px);
      -webkit-backdrop-filter: blur(10px);
      white-space: nowrap;

             &.btn-secondary {
         background: rgba(59, 130, 246, 0.3);
         color: #dbeafe;
         border: 1px solid rgba(59, 130, 246, 0.4);

         &:hover {
           background: rgba(59, 130, 246, 0.5);
           color: #ffffff;
           border-color: rgba(59, 130, 246, 0.6);
           transform: translateY(-1px);
           box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
         }
       }

       &.btn-primary {
         background: rgba(59, 130, 246, 0.3);
         color: #dbeafe;
         border: 1px solid rgba(59, 130, 246, 0.4);

         &:hover {
           background: rgba(59, 130, 246, 0.5);
           color: #ffffff;
           border-color: rgba(59, 130, 246, 0.6);
           transform: translateY(-1px);
           box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
         }
       }
    }

    h2 {
      color: #ffffff;
      font-size: 1.35rem;
      margin: 0;
      text-align: center;
      flex: 1;
    }
  }

  .score-card {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 1.5rem;
    background: rgba(31, 41, 55, 0.9);
    border-radius: 10px;
    padding: 0.875rem 1.25rem;
    border: 2px solid rgba(255, 255, 255, 0.1);
    transition: all 0.3s ease;
    max-width: 450px;
    margin: 0 auto;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
    }

    .score-section {
      text-align: center;
      flex: 1;

      .score-label {
        color: #9ca3af;
        font-size: 0.75rem;
        margin-bottom: 0.25rem;
      }

      .score-value {
        font-size: 1.5rem;
        font-weight: 700;
        color: #3b82f6;
        line-height: 1.2;
      }

      .score-level {
        color: #10b981;
        font-size: 0.65rem;
        margin-top: 0.25rem;
        font-weight: 600;
      }
    }

    .divider {
      width: 1px;
      height: 40px;
      background: rgba(255, 255, 255, 0.1);
    }
  }
}

.questions-list {
  max-width: 900px;
  margin: 0 auto;
  padding: 0 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.question-item {
  background: rgba(31, 41, 55, 0.9);
  border-radius: 10px;
  padding: 1rem;
  border: 2px solid transparent;
  transition: all 0.3s ease;

  &.correct {
    border-color: rgba(16, 185, 129, 0.5);
    background: rgba(16, 185, 129, 0.05);
  }

  &.incorrect {
    border-color: rgba(239, 68, 68, 0.5);
    background: rgba(239, 68, 68, 0.05);
  }

  .question-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.75rem;
    padding-bottom: 0.5rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .question-number {
      font-size: 0.95rem;
      font-weight: 600;
      color: #3b82f6;
    }

    .result-badge {
      padding: 0.25rem 0.625rem;
      border-radius: 4px;
      font-size: 0.75rem;
      font-weight: 600;

      &.correct-badge {
        background: rgba(16, 185, 129, 0.2);
        color: #10b981;
      }

      &.incorrect-badge {
        background: rgba(239, 68, 68, 0.2);
        color: #ef4444;
      }
    }
  }

  .question-text {
    font-size: 0.95rem;
    line-height: 1.5;
    color: #ffffff;
    margin-bottom: 0.75rem;
    font-weight: 500;
  }

  .options-list {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }

  .option-item {
    display: flex;
    align-items: center;
    padding: 0.75rem;
    background: rgba(55, 65, 81, 0.5);
    border-radius: 6px;
    border: 2px solid transparent;
    transition: all 0.3s ease;
    position: relative;

    &.user-selected {
      border-color: #3b82f6;
      background: rgba(59, 130, 246, 0.1);
    }

    &.correct-answer {
      border-color: #10b981;
      background: rgba(16, 185, 129, 0.1);
    }

    &.user-selected.correct-answer {
      border-color: #10b981;
      background: rgba(16, 185, 129, 0.15);
    }

    .option-label {
      font-weight: 600;
      color: #3b82f6;
      margin-right: 0.5rem;
      min-width: 20px;
      font-size: 0.875rem;
    }

    .option-text {
      flex: 1;
      color: #ffffff;
      font-size: 0.875rem;
    }

    .tag {
      padding: 0.2rem 0.4rem;
      border-radius: 3px;
      font-size: 0.65rem;
      font-weight: 600;
      margin-left: 0.5rem;
      white-space: nowrap;
    }

    .user-tag {
      background: rgba(59, 130, 246, 0.2);
      color: #60a5fa;
    }

    .correct-tag {
      background: rgba(16, 185, 129, 0.2);
      color: #34d399;
    }
  }
}

@media (max-width: 768px) {
  .result-container {
    padding: 80px 1rem 30px;
  }

  .ai-comment {
    padding: 0 1rem;
    margin-bottom: 1rem;

    .comment-header {
      gap: 0.5rem;

      .ai-icon {
        font-size: 1.25rem;
      }

      h3 {
        font-size: 1.1rem;
      }
    }

    .comment-content {
      padding: 0.875rem 1rem;

      p {
        font-size: 0.85rem;
      }
    }
  }

  .result-overview {
    padding: 0 1rem;

    .result-header {
      gap: 0.5rem;

      button {
        padding: 0.45rem 0.9rem;
        font-size: 0.75rem;
      }

      h2 {
        font-size: 1.2rem;
      }
    }

    .score-card {
      padding: 0.75rem 1rem;
      gap: 1rem;

      .score-section {
        .score-label {
          font-size: 0.7rem;
        }

        .score-value {
          font-size: 1.25rem;
        }

        .score-level {
          font-size: 0.6rem;
        }
      }

      .divider {
        height: 35px;
      }
    }
  }

  .questions-list {
    padding: 0 1rem;
  }

  .question-item {
    padding: 1rem;
  }
}
</style>
